package com.cskaoyan.service;

import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.beanwx.bo.OrderBaseBo;
import com.cskaoyan.beanwx.bo.OrderCommentBo;
import com.cskaoyan.beanwx.pojo.HandleOption;
import com.cskaoyan.beanwx.vo.OrderDetailVo;
import com.cskaoyan.beanwx.vo.OrderGoodsVo;
import com.cskaoyan.beanwx.vo.OrderListVo;
import com.cskaoyan.beanwx.vo.UserIndexVo;
import com.cskaoyan.dao.*;
import com.cskaoyan.utils.OrderStateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.System;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: lds
 * @clsss: OrderServiceImpl
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    GrouponMapper grouponMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    OrderGoodsMapper orderGoodsMapper;

    @Override
    public UserIndexVo queryUserOrder(Integer id) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andUserIdEqualTo(id);
        criteria.andDeletedEqualTo(false);
        List<Order> orders = null;
        try {
            orders = orderMapper.selectByExample(orderExample);
        } catch (Exception e) {
            return null;
        }

        int unrev = 0;
        int uncomment = 0;
        int unpaid = 0;
        int unship = 0;
        int commented = 0;
        for (Order order : orders) {
            if (order.getOrderStatus() == (short) 101) {
                unpaid = unpaid + 1;

            }
            if (order.getOrderStatus() == (short) 201) {
                unship = unship + 1;

            }
            if (order.getOrderStatus() == (short) 301) {
                unrev = unrev + 1;

            }
            if (order.getOrderStatus() == (short) 401) {
                //判断是否有评论
                CommentExample commentExample = new CommentExample();
                CommentExample.Criteria criteria1 = commentExample.createCriteria();
                criteria1.andValueIdEqualTo(order.getId());
                List<Comment> comments = commentMapper.selectByExample(commentExample);
                if (comments.size() <= 0) {
                    uncomment = uncomment + 1;
                }

            }
            if (order.getOrderStatus() == (short) 402) {
                commented += 1;
            }
        }

        UserIndexVo.OrderBean orderBean = new UserIndexVo.OrderBean();
        orderBean.setUncomment(uncomment);
        orderBean.setUnpaid(unpaid);
        orderBean.setUnrecv(unrev);
        orderBean.setUnship(unship);
        orderBean.setCommented(commented);
        UserIndexVo userIndexVo = new UserIndexVo();
        userIndexVo.setOrder(orderBean);
        return userIndexVo;
    }

    @Override
    public OrderListVo queryUserOrderDetail(OrderBaseBo orderBaseBo, User user) {
        Integer showType = orderBaseBo.getShowType();
        Integer page = orderBaseBo.getPage();
        Integer size = orderBaseBo.getSize();

        //分页
        PageHelper.startPage(page, size);
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andUserIdEqualTo(user.getId());
        criteria.andDeletedEqualTo(false);
        switch (showType) {
            case 0:
                break;
            case 1:
                criteria.andOrderStatusEqualTo((short) 101);
                break;
            case 2:
                criteria.andOrderStatusEqualTo((short) 201);
                break;
            case 3:
                criteria.andOrderStatusEqualTo((short) 301);
                break;
            case 4:
                criteria.andOrderStatusEqualTo((short) 401);
                break;
            case 5:
                criteria.andOrderStatusEqualTo((short) 402);
                break;
        }

        List<Order> orders = null;
        try {
            orders = orderMapper.selectByExample(orderExample);
        } catch (Exception e) {
            return null;
        }
        PageInfo<Order> orderPageInfo = new PageInfo<>(orders);
        int pageInfoSize = orderPageInfo.getSize();
        int size1 = orders.size();
        LinkedList<OrderListVo.DataBean> dataBeans = new LinkedList<>();
        for (Order order : orders) {
            OrderListVo.DataBean dataBean = new OrderListVo.DataBean();
            //orderStatusText
            String statusText = OrderStateUtil.getStatusText(order.getOrderStatus());
            dataBean.setOrderStatusText(statusText);
            //查询订单是否是参加团购
            boolean b = judgeOrderGroup(order);
            dataBean.setIsGroupin(b);
            //order sn
            String orderSn = order.getOrderSn();
            dataBean.setOrderSn(orderSn);
            //actualPrice
            BigDecimal actualPrice = order.getActualPrice();
            dataBean.setActualPrice(actualPrice);
            //id
            Integer id = order.getId();
            dataBean.setId(id);
            //HandleOption
            HandleOption handleOption = getHandleOption(order);
            if (order.getOrderStatus() == 401) {
                //判断是否评论
                CommentExample commentExample = new CommentExample();
                CommentExample.Criteria criteria1 = commentExample.createCriteria();
                criteria1.andValueIdEqualTo(order.getId());
                List<Comment> comments = commentMapper.selectByExample(commentExample);
                if (comments.size() > 0) {
                    handleOption.setComment(false);
                    order.setOrderStatus((short) 402);
                    Order changeOrderStatus = new Order();
                    changeOrderStatus.setOrderStatus((short) 402);
                    OrderExample orderExample1 = new OrderExample();
                    orderMapper.updateByExampleSelective(changeOrderStatus, orderExample1);
                }
            }

            dataBean.setHandleOption(handleOption);
            //goodList
            OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
            OrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
            criteria1.andOrderIdEqualTo(order.getId());

            List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
            dataBean.setGoodsList(orderGoods);
            dataBeans.add(dataBean);
        }
        OrderListVo orderListVo = new OrderListVo();
        orderListVo.setCount(size1);
        orderListVo.setTotalPages(pageInfoSize);
        orderListVo.setData(dataBeans);

        return orderListVo;
    }

    private HandleOption getHandleOption(Order order) {
        //handleOption
        HandleOption handleOptionBean = new HandleOption();
        switch (order.getOrderStatus()) {
            case 101:
                //handleOption cancel
                handleOptionBean.setCancel(true);
                //pay
                handleOptionBean.setPay(true);
                //handleOption delete
                handleOptionBean.setDelete(false);
                //handleOption comment
                handleOptionBean.setComment(false);
                //handleOption confirm
                handleOptionBean.setConfirm(false);
                //handleOption refund
                handleOptionBean.setRefund(false);
                //handleOption rebuy
                handleOptionBean.setRebuy(false);
                break;
            case 102:
                //handleOption cancel
                handleOptionBean.setCancel(false);
                //pay
                handleOptionBean.setPay(false);
                //handleOption delete
                handleOptionBean.setDelete(true);
                //handleOption comment
                handleOptionBean.setComment(false);
                //handleOption confirm
                handleOptionBean.setConfirm(false);
                //handleOption refund
                handleOptionBean.setRefund(false);
                //handleOption rebuy
                handleOptionBean.setRebuy(false);
                break;
            case 103:
                //handleOption cancel
                handleOptionBean.setCancel(false);
                //pay
                handleOptionBean.setPay(false);
                //handleOption delete
                handleOptionBean.setDelete(true);
                //handleOption comment
                handleOptionBean.setComment(false);
                //handleOption confirm
                handleOptionBean.setConfirm(false);
                //handleOption refund
                handleOptionBean.setRefund(false);
                //handleOption rebuy
                handleOptionBean.setRebuy(false);
                break;
            case 201:
                //handleOption cancel
                handleOptionBean.setCancel(true);
                //pay
                handleOptionBean.setPay(false);
                //handleOption delete
                handleOptionBean.setDelete(false);
                //handleOption comment
                handleOptionBean.setComment(false);
                //handleOption confirm
                handleOptionBean.setConfirm(false);
                //handleOption refund
                handleOptionBean.setRefund(false);
                //handleOption rebuy
                handleOptionBean.setRebuy(false);
                break;
            case 202:
                //handleOption cancel
                handleOptionBean.setCancel(true);
                //pay
                handleOptionBean.setPay(false);
                //handleOption delete
                handleOptionBean.setDelete(false);
                //handleOption comment
                handleOptionBean.setComment(false);
                //handleOption confirm
                handleOptionBean.setConfirm(false);
                //handleOption refund
                handleOptionBean.setRefund(false);
                //handleOption rebuy
                handleOptionBean.setRebuy(false);
                break;
            case 203:
                //handleOption cancel
                handleOptionBean.setCancel(false);
                //pay
                handleOptionBean.setPay(false);
                //handleOption delete
                handleOptionBean.setDelete(true);
                //handleOption comment
                handleOptionBean.setComment(false);
                //handleOption confirm
                handleOptionBean.setConfirm(false);
                //handleOption refund
                handleOptionBean.setRefund(false);
                //handleOption rebuy
                handleOptionBean.setRebuy(false);
                break;
            case 301:
                //handleOption cancel
                handleOptionBean.setCancel(false);
                //pay
                handleOptionBean.setPay(false);
                //handleOption delete
                handleOptionBean.setDelete(false);
                //handleOption comment
                handleOptionBean.setComment(false);
                //handleOption confirm
                handleOptionBean.setConfirm(true);
                //handleOption refund
                handleOptionBean.setRefund(false);
                //handleOption rebuy
                handleOptionBean.setRebuy(false);
                break;
            case 401:
                //handleOption cancel
                handleOptionBean.setCancel(false);
                //pay
                handleOptionBean.setPay(false);
                //handleOption delete
                handleOptionBean.setDelete(false);
                //handleOption comment
                handleOptionBean.setComment(true);
                //handleOption confirm
                handleOptionBean.setConfirm(false);
                //handleOption refund
                handleOptionBean.setRefund(true);
                //handleOption rebuy
                handleOptionBean.setRebuy(true);
                break;
            case 402:
                //handleOption cancel
                handleOptionBean.setCancel(false);
                //pay
                handleOptionBean.setPay(false);
                //handleOption delete
                handleOptionBean.setDelete(true);
                //handleOption comment
                handleOptionBean.setComment(false);
                //handleOption confirm
                handleOptionBean.setConfirm(false);
                //handleOption refund
                handleOptionBean.setRefund(false);
                //handleOption rebuy
                handleOptionBean.setRebuy(true);
                break;

        }

        return handleOptionBean;
    }

    @Override
    public OrderDetailVo queryOrderByOrderId(User user, Integer orderId) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        criteria.andDeletedEqualTo(false);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        Order order = orders.get(0);


        HandleOption handleOption = getHandleOption(order);
        if (order.getOrderStatus() == 401) {
            //判断是否评论
            CommentExample commentExample = new CommentExample();
            CommentExample.Criteria criteria1 = commentExample.createCriteria();
            criteria1.andValueIdEqualTo(order.getId());
            List<Comment> comments = commentMapper.selectByExample(commentExample);
            if (comments.size() > 0) {
                handleOption.setComment(false);
                order.setOrderStatus((short) 402);
            }
        }
        String statusText = OrderStateUtil.getStatusText(order.getOrderStatus());
        OrderDetailVo.OrderInfoBean orderInfoBean = new OrderDetailVo.OrderInfoBean();
        orderInfoBean.setHandleOption(handleOption);
        orderInfoBean.setConsignee(order.getConsignee());
        orderInfoBean.setAddress(order.getAddress());
        orderInfoBean.setAddTime(order.getAddTime());
        orderInfoBean.setOrderSn(order.getOrderSn());
        orderInfoBean.setActualPrice(order.getActualPrice());
        orderInfoBean.setMobile(order.getMobile());
        orderInfoBean.setOrderStatusText(statusText);
        orderInfoBean.setGoodsPrice(order.getGoodsPrice());
        orderInfoBean.setCouponPrice(order.getCouponPrice());
        orderInfoBean.setId(order.getId());
        orderInfoBean.setFreightPrice(order.getFreightPrice());
        orderInfoBean.setJifen(orderInfoBean.getGoodsPrice()
                .subtract(orderInfoBean.getFreightPrice())
                .subtract(orderInfoBean.getCouponPrice())
                .subtract(orderInfoBean.getActualPrice()));


        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
        criteria1.andOrderIdEqualTo(order.getId());
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setOrderGoods(orderGoods);
        orderDetailVo.setOrderInfo(orderInfoBean);
        return orderDetailVo;
    }

    @Override
    public Integer changeCancelOrder(User user, Integer orderId) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        Order order = new Order();
        order.setOrderStatus((short) 102);
        int i = orderMapper.updateByExampleSelective(order, orderExample);
        //更新货物数量
        updateGoods(orderId);
        return i;
    }

    //更新货物数量
    private void updateGoods(Integer orderId) {
        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria = orderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        for (OrderGoods orderGood : orderGoods) {
            Short number = orderGood.getNumber();
            Integer productId = orderGood.getProductId();

            GoodsProductExample goodsProductExample = new GoodsProductExample();
            GoodsProductExample.Criteria criteria1 = goodsProductExample.createCriteria();
            criteria1.andIdEqualTo(productId);
            List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
            GoodsProduct goodsProduct1 = goodsProducts.get(0);
            Integer number1 = goodsProduct1.getNumber();

            GoodsProduct goodsProduct = new GoodsProduct();
            goodsProduct.setNumber(number1 + number);
            GoodsProductExample goodsProductExample1 = new GoodsProductExample();
            GoodsProductExample.Criteria criteria2 = goodsProductExample1.createCriteria();
            criteria2.andGoodsIdEqualTo(productId);
            int i = goodsProductMapper.updateByExample(goodsProduct, goodsProductExample1);

        }


    }

    @Override
    public Integer changeConfirmOrder(User user, Integer orderId) {

        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        Order order = new Order();
        order.setOrderStatus((short) 401);
        int i = orderMapper.updateByExampleSelective(order, orderExample);

        return i;
    }

    @Override
    public Integer changeRefundOrder(User user, Integer orderId) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        Order order = new Order();
        order.setOrderStatus((short) 202);
        int i = orderMapper.updateByExampleSelective(order, orderExample);
        //更新货物数量
        updateGoods(orderId);
        return i;

    }

    @Override
    public Integer changeDeleteOrder(User user, Integer orderId) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        Order order = new Order();
        order.setDeleted(true);
        int i = orderMapper.updateByExampleSelective(order, orderExample);

        return i;
    }

    @Override
    public OrderGoodsVo queryGoodsOrder(Integer orderId, Integer goodsId, User user) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        Order order = orders.get(0);


        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria1 = goodsExample.createCriteria();
        criteria1.andIdEqualTo(goodsId);
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);
        Goods good = goods.get(0);

        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria criteria2 = goodsProductExample.createCriteria();
        criteria2.andGoodsIdEqualTo(goodsId);
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        GoodsProduct goodsProduct = goodsProducts.get(0);

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        OrderGoodsExample.Criteria criteria3 = orderGoodsExample.createCriteria();
        criteria3.andGoodsIdEqualTo(goodsId);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        OrderGoods orderGood = orderGoods.get(0);
        LinkedList<String> specifications = new LinkedList<>();
        String[] specifications1 = orderGood.getSpecifications();
        for (String s : specifications1) {
            specifications.add(s);

        }

        OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
        orderGoodsVo.setId(order.getId());
        orderGoodsVo.setOrderId(order.getId());
        orderGoodsVo.setGoodsId(good.getId());
        orderGoodsVo.setGoodsName(good.getName());
        orderGoodsVo.setGoodsSn(good.getGoodsSn());
        orderGoodsVo.setProductId(goodsProduct.getId());
        orderGoodsVo.setPicUrl(goodsProduct.getUrl());
        orderGoodsVo.setComment(0);

        orderGoodsVo.setUpdateTime(order.getUpdateTime());
        orderGoodsVo.setAddTime(order.getAddTime());

        orderGoodsVo.setDeleted(false);

        orderGoodsVo.setSpecifications(specifications);


        return orderGoodsVo;
    }

    @Override
    public Integer addComment(OrderCommentBo orderCommentBo, User user) {

        Comment comment = new Comment();
        comment.setId(null);
        comment.setValueId(orderCommentBo.getOrderGoodsId());
        comment.setType((byte) 0);
        comment.setContent(orderCommentBo.getContent());
        comment.setUserId(user.getId());
        List<String> picUrls = orderCommentBo.getPicUrls();
        if (picUrls.size() > 0) {
            comment.setHasPicture(true);
            String[] strings = new String[picUrls.size()];
            for (int i = 0; i < picUrls.size(); i++) {
                strings[i] = picUrls.get(i);
            }
            comment.setPicUrls(strings);
        } else {
            comment.setHasPicture(false);
            String[] strings = new String[picUrls.size()];
            comment.setPicUrls(strings);
        }


        comment.setStar((short) orderCommentBo.getStar());
        comment.setAddTime(new Date(System.currentTimeMillis()));
        comment.setUpdateTime(new Date(System.currentTimeMillis()));
        comment.setDeleted(false);

        Integer i = commentMapper.insertSelective(comment);
        System.err.println(i);

        return i;
    }

    @Override
    public Integer changePrepayOrder(User user, Integer orderId) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        Order order = new Order();
//        order.setOrderStatus((short) 201);
        int i = orderMapper.updateByExampleSelective(order, orderExample);

        return i;

    }

    @Override
    public int addOrder(Order order) {
        return orderMapper.insertSelective(order);
    }

    @Override
    public int addOrderGoods(OrderGoods orderGoods) {
        return orderGoodsMapper.insertSelective(orderGoods);
    }

    @Override
    public Order queryOrderById(int orderId1) {
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria().andIdEqualTo(orderId1).andDeletedEqualTo(false);

        List<Order> orders = orderMapper.selectByExample(orderExample);
        if (orders.size() != 0) {
            return orders.get(0);
        }
        return null;
    }


    private boolean judgeOrderGroup(Order order) {

        GrouponExample grouponExample = new GrouponExample();
        GrouponExample.Criteria criteria = grouponExample.createCriteria();
        criteria.andOrderIdEqualTo(order.getId());
        List<Groupon> groupons = grouponMapper.selectByExample(grouponExample);
        boolean groupon = false;
        if (groupons.size() == 1) {
            groupon = true;
        } else {
            groupon = false;
        }
        return groupon;
    }
}
